package frame.options.simulation.create.splitting;

import ilog.concert.IloException;
import ilog.cplex.IloCplex;

import java.util.List;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import model.algorithms.splitting.SplittingAlgorithm;

import com.nexes.wizard.WizardPanelDescriptor;

import frame.options.simulation.create.CreateSimulationWizard;
import frame.options.simulation.create.backup.BackupDescriptor;
import frame.options.simulation.create.coordinated.CoordinatedDescriptor;

public class SplittingDescriptor extends WizardPanelDescriptor implements ListSelectionListener
{
	public static final String IDENTIFIER = "SplittingDescriptor";
	
	private SplittingPanel splittingPanel;
	public SplittingPanel getSplittingPanel(){ return splittingPanel; }
	public void setSplittingPanel( SplittingPanel splittingPanel ){ this.splittingPanel = splittingPanel; }
	
	public SplittingDescriptor( List< SplittingAlgorithm > splittingAlgorithms )
    {
    	this.setSplittingPanel( new SplittingPanel( splittingAlgorithms ) );
		this.getSplittingPanel().addListeners( this );
		
		this.setPanelDescriptorIdentifier( IDENTIFIER );
        this.setPanelComponent( this.getSplittingPanel() );
    }
	
	@Override
	public Object getBackPanelDescriptor()
	{
		return BackupDescriptor.IDENTIFIER;
	}
	
    @Override
	public Object getNextPanelDescriptor()
    {
    	return CoordinatedDescriptor.IDENTIFIER;
    }
    
    @Override
	public void aboutToDisplayPanel()
    {    	
    	this.setNextFinishButton();
    }
    
	@Override
	public void valueChanged( ListSelectionEvent listSelectionEvent )
	{
		this.setNextFinishButton();
	}
	
	private void setNextFinishButton()
	{
		this.getSplittingPanel().getErrorLabel().setText( "" );
		this.getWizard().setNextFinishButtonEnabled( false );
		
    	if( this.getSplittingPanel().getSplittingAlgorithmsList().getSelectedValuesList().size() == 1 )
    	{
    		if( this.isCplexInstalled() ||
    			( !this.isCplexInstalled() && !this.getSplittingPanel().getSplittingAlgorithmsList().getSelectedValuesList().get( 0 ).getName().equals( "Exact" ) ) )
    		{
        		( (CreateSimulationWizard) this.getWizard() ).setSplittingAlgorithm( this.getSplittingPanel().getSelectedSplittingAlgorithm() );
        		getWizard().setNextFinishButtonEnabled( true );
    		}
    		else
    		{
    			this.getSplittingPanel().getErrorLabel().setText( "\"Exact\" is not selectable because Cplex is not installed" );
    		}
    	}
	}
	
	private boolean isCplexInstalled()
	{
		try
		{
			new IloCplex();
			
			return true;
		}
		catch( UnsatisfiedLinkError unsatisfiedLinkError )
		{
			return false;
		}
		catch( IloException e )
		{
			return false;
		}
	}
	
}
